//
//  AssetTablePicker.m
//
//  Created by Matt Tuzzolo on 2/15/11.
//  Copyright 2011 ELC Technologies. All rights reserved.
//

#import "ELCAssetTablePicker.h"
#import "ELCAssetCell.h"
#import "ELCAsset.h"
#import "ELCAlbumPickerController.h"

#import "PublicMethodEngine.h"
#import "SDDataCache.h"


@implementation ELCAssetTablePicker

@synthesize parent;
@synthesize selectedAssetsLabel;
@synthesize assetGroup;
@synthesize selAllButton;

@synthesize assetDict;
@synthesize sortedKeyArray;

-(void)viewDidLoad {

	[self.tableView setSeparatorColor:[UIColor clearColor]];
	[self.tableView setAllowsSelection:NO];
  
    if (assetDict == nil) {
        assetDict = [[NSMutableDictionary alloc] init];
    }
    sortedKeyArray = nil;
    
    [self.view setBackgroundColor:BackGround_Color];
    
    //发送评论
//    UIImage *sendBtnBackground = [[UIImage imageNamed:@"topbuttonBG_iphone.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
//    UIImage *selectedSendBtnBackground = [[UIImage imageNamed:@"topbuttonBG1_iphone.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
//    
//    selAllButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    selAllButton.tag = 1;
//    selAllButton.frame = CGRectMake(0, 0, 40, 30);
//    selAllButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
//    [selAllButton setTitle:@"全选" forState:UIControlStateNormal];
//    [selAllButton setTitle:@"取消" forState:UIControlStateSelected];
//    
//    [selAllButton setTitleShadowColor:[UIColor colorWithWhite:0 alpha:0.4] forState:UIControlStateNormal];
//    selAllButton.titleLabel.shadowOffset = CGSizeMake (0.0, -1.0);
//    selAllButton.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
//    
//    [selAllButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [selAllButton addTarget:self action:@selector(selectAllAction:) forControlEvents:UIControlEventTouchUpInside];
//    [selAllButton setBackgroundImage:sendBtnBackground forState:UIControlStateNormal];
//    [selAllButton setBackgroundImage:selectedSendBtnBackground forState:UIControlStateSelected];
//    
//    UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    doneBtn.frame = CGRectMake(50, 0, 40, 30);
//    doneBtn.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
//    [doneBtn setTitle:@"确定" forState:UIControlStateNormal];
//    
//    [doneBtn setTitleShadowColor:[UIColor colorWithWhite:0 alpha:0.4] forState:UIControlStateNormal];
//    doneBtn.titleLabel.shadowOffset = CGSizeMake (0.0, -1.0);
//    doneBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
//    
//    [doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [doneBtn addTarget:self action:@selector(doneAction:) forControlEvents:UIControlEventTouchUpInside];
//    [doneBtn setBackgroundImage:sendBtnBackground forState:UIControlStateNormal];
//    [doneBtn setBackgroundImage:selectedSendBtnBackground forState:UIControlStateSelected];
//    
//    
//    UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 90, 30)];
//    
//    [buttonView addSubview:doneBtn];
//    [buttonView addSubview:selAllButton];
//    
//    selAllButton.hidden = YES;
//    
//    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonView];
    
    
    UIBarButtonItem *doneButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(doneAction:)];
    
    [self.navigationItem setRightBarButtonItem:doneButtonItem];
    [doneButtonItem release];
    
    
    
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(popViewController:)];
	[self.navigationItem setLeftBarButtonItem:backButton];
	[backButton release];
    
    
	[self.navigationItem setTitle:@"选择照片"];
    [LoadingView showMessageLoadingViewWith:@"读取中…" autoHide:NO];

	[self performSelectorInBackground:@selector(preparePhotos) withObject:nil];
    
    // Show partial while full list loads
	//[self.tableView performSelector:@selector(reloadData) withObject:nil afterDelay:.5];
}

-(void)preparePhotos {
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	
    NSLog(@"enumerating photos");
    [self.assetGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) 
     {         
         if(result == nil) 
         {
             return;
         }
         
         ELCAsset *elcAsset = [[[ELCAsset alloc] initWithAsset:result] autorelease];
         [elcAsset setParent:self];
         //[self.elcAssets addObject:elcAsset];
         
         ALAsset *asset = elcAsset.asset;
         NSDate *date = [asset valueForProperty:ALAssetPropertyDate];

         NSString *dateString = [[PublicMethodEngine sharedPublicMethodEngine] NSDateToNSTring:date];
         
         CLog(@"Date %@", dateString);
         
         NSString *monthKey = [dateString substringToIndex:7];
         CLog(@"MonthKey %@", monthKey);
         NSMutableArray *monthArray = [assetDict objectForKey:monthKey];
         if (monthArray == nil) {
             monthArray = [[NSMutableArray alloc] init];
             [assetDict setObject:monthArray forKey:monthKey];
             [monthArray release];
         }
         [monthArray addObject:elcAsset];
   
     }];    
    
    NSLog(@"done enumerating photos");
	
	[self.tableView reloadData];
	[self.navigationItem setTitle:@"选择照片"];
    [LoadingView hideWithAnimated:YES];
    
    [pool release];
    

}

- (void)cancleSelAll
{
    [selAllButton setSelected:NO];
    selAllButton.tag = 1;
}



- (void)doneAction:(id)sender {
	[LoadingView showMessageLoadingViewWith:@"保存中，请稍等…" autoHide:NO];
    
    CLog(@"Action done!——1");

    //[self actionDone];
    [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(actionDone) userInfo:nil repeats:NO];
    
    CLog(@"Action done!——2");

    
    
    
}

- (void)actionDone
{
    CLog(@"Action done!——3");
    
    NSMutableArray *selectedAssetsImages = [[[NSMutableArray alloc] init] autorelease];
    
    for (NSString *key in [assetDict allKeys]) {
        NSArray *array = [assetDict objectForKey:key];
        if (array != nil) {
            for(ELCAsset *elcAsset in array) 
            {		
                if([elcAsset selected]) {
                    
                    ALAsset *asset = [elcAsset asset];
                    [selectedAssetsImages addObject:asset];
                    
//                    NSURL *url = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:[[[asset valueForProperty:ALAssetPropertyURLs] allKeys] objectAtIndex:0]];
//                    NSString *urlStr = [url absoluteString];
//                    
//                    if (urlStr) {
//                        UIImage *fullImage = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]];
//                        
//                        UIImage *image = [fullImage copy];
//                        [fullImage release];
//                        
//                        NSData *imageData = [[PublicMethodEngine sharedPublicMethodEngine] compresImageDataWith:image maxPix:PHOTO_MAXPIX];
//                        
//                        [[SDDataCache sharedDataCache:kImageCache_Locale_Album] saveDataToDiskWith:imageData saveKey:urlStr];
//                        
//                        [image release];
//                    }

                }
            }
        }
        
    }
    
    [(ELCAlbumPickerController*)self.parent selectedAssets:selectedAssetsImages];
}


- (NSString *)getAppendKey
{
    return [(ELCAlbumPickerController*)self.parent getAppendKey];
}

- (void)selectAllAction:(id)sender
{
    [LoadingView showDurationMessageLoadingViewWith:1.5 message:@"暂不支持全选哦！"];
    
    return;
    
    UIButton *buttonItem = (UIButton *)sender;

    NSInteger tag = buttonItem.tag;
    
    //大于0全选，其它为取消全选
    if (tag >0) {
        for (NSString *key in [assetDict allKeys]) {
            NSArray *array = [assetDict objectForKey:key];
            if (array != nil) {
                for(ELCAsset *elcAsset in array) 
                {		
                    if(![elcAsset selected]) {
                        
                        [elcAsset setSelected:YES];
                    }
                }
            }
            
        }
        
        
        [buttonItem setSelected:YES];
        buttonItem.tag = 0;
    }
    else {
        
        for (NSString *key in [assetDict allKeys]) {
            NSArray *array = [assetDict objectForKey:key];
            if (array != nil) {
                for(ELCAsset *elcAsset in array) 
                {		
                    if([elcAsset selected]) {
                        
                        [elcAsset setSelected:NO];
                    }
                }
            }
            
        }
        
        [buttonItem setSelected:NO];
        buttonItem.tag = 1;
    }
    

}



- (NSString *)getKeyWith:(NSArray *)keyArray keyIndex:(NSInteger)keyIndex
{
    if (sortedKeyArray == nil) {
        NSArray *newArray = [keyArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
        
        sortedKeyArray = [[NSArray alloc] initWithArray:newArray];
    }
    //NSArray *newArray = [keyArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    NSString *keyStr = [sortedKeyArray objectAtIndex:keyIndex];
    
    return keyStr;
}

#pragma mark - Nav Controller Delegate
- (void)popViewController:(id)sender
{
    CLog(@"popViewController");
    
    NSString *appendKey = [self getAppendKey];
    
    [LoadingView showMessageLoadingViewWith:@"请稍等…" autoHide:NO];
    
    for (NSString *key in [assetDict allKeys]) {
        NSArray *array = [assetDict objectForKey:key];
        if (array != nil) {
            
            //在取消的情况下将缓存删除
            for(ELCAsset *elcAsset in array) 
            {		
                if([elcAsset selected]) {
                    ALAsset *asset = [elcAsset asset];
                    
                    NSURL *url = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:[[[asset valueForProperty:ALAssetPropertyURLs] allKeys] objectAtIndex:0]];
                    NSString *urlStr = [NSString stringWithFormat:@"%@%@", appendKey, [url absoluteString]];
                    
                    if (urlStr) {
                        [[SDDataCache sharedDataCache:kImageCache_Locale_Album] removeDataForKey:urlStr];
                    }
                }
            }
        }
    }
    
    [LoadingView hideWithAnimated:NO];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{
    CLog(@"Elcasset table picker should pop !");
    return YES;
}

- (void)navigationBar:(UINavigationBar *)navigationBar didPopItem:(UINavigationItem *)item
{
    
    //返回后晴空缓存内容
    
    CLog(@"Elcasset table picker pop !");
    
    
}


#pragma mark UITableViewDataSource Delegate Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    NSArray *keyArray = [assetDict allKeys];
    
    if (keyArray) {
        return [keyArray count];
    }
    else {
        return 0;
    }

    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSString *key = [self getKeyWith:[assetDict allKeys] keyIndex:section];
    NSArray *array = [assetDict objectForKey:key];
    
    if (array) {
        return ceil([array count] / 4.0);
    }
    else {
        return 0;
    }
    
    //return ceil([self.assetGroup numberOfAssets] / 4.0);
}

- (NSArray*)assetsForIndexPath:(NSIndexPath*)_indexPath {

	// NSLog(@"Getting assets for %d to %d with array count %d", index, maxIndex, [assets count]);
    
    NSInteger section = _indexPath.section;
    NSInteger row = _indexPath.row;

    NSString *key = [self getKeyWith:[assetDict allKeys] keyIndex:section];
    NSArray *array = [assetDict objectForKey:key];
    
    int index = (row*4);
	int maxIndex = (row*4+3);
    
	if(maxIndex < [array count]) {
        
		return [NSArray arrayWithObjects:[array objectAtIndex:index],
				[array objectAtIndex:index+1],
				[array objectAtIndex:index+2],
				[array objectAtIndex:index+3],
				nil];
	}
    
	else if(maxIndex-1 < [array count]) {
        
		return [NSArray arrayWithObjects:[array objectAtIndex:index],
				[array objectAtIndex:index+1],
				[array objectAtIndex:index+2],
				nil];
	}
    
	else if(maxIndex-2 < [array count]) {
        
		return [NSArray arrayWithObjects:[array objectAtIndex:index],
				[array objectAtIndex:index+1],
				nil];
	}
    
	else if(maxIndex-3 < [array count]) {
        
		return [NSArray arrayWithObject:[array objectAtIndex:index]];
	}
    
	return nil;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
        
    ELCAssetCell *cell = (ELCAssetCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) 
    {		        
        cell = [[[ELCAssetCell alloc] initWithAssets:[self assetsForIndexPath:indexPath] reuseIdentifier:CellIdentifier] autorelease];
    }	
	else 
    {		
		[cell setAssets:[self assetsForIndexPath:indexPath]];
	}
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	return 79;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    NSString *key = [self getKeyWith:[assetDict allKeys] keyIndex:section];
    
    return key;
}


- (int)totalSelectedAssets {
    
    int count = 0;
    
    for (NSString *key in [assetDict allKeys]) {
        NSArray *array = [assetDict objectForKey:key];
        if (array != nil) {
            for(ELCAsset *elcAsset in array) 
            {		
                if([elcAsset selected]) 
                {            
                    count++;	
                }
            }
        }
        
    }
    
    return count;
}

- (void)dealloc 
{
    [assetDict release];
    if (sortedKeyArray != nil) {
        [sortedKeyArray release];
    }
    
    [selectedAssetsLabel release];
    
    [selAllButton release];

    CLog(@"ELCAssetTablePicker dealloc");
    [super dealloc];    
}

@end
